package com.fly.core.auth;

import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.luck.entity.JsonResult;
import com.fly.luck.service.TokenService;

/**
 * 
 * AuthInterceptor
 * 
 * @author 00fly
 * @version [版本号, 2019年7月21日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter
{
    @Autowired
    TokenService tokenService;
    
    private ObjectMapper mapper = new ObjectMapper();
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception
    {
        String token = (String)request.getSession().getAttribute("token");
        if (!tokenService.valide(token))
        {
            JsonResult<?> result = JsonResult.error("系统登录状态失效，请重新登录");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            response.getWriter().print(mapper.writeValueAsString(result));
            return false;
        }
        return true;
    }
}